<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends BaseController {
    public function index(){
    	$user = M('user');
    	
    	//只有超级管理员才能到看到自己$power=4
    	
    	$power=$_SESSION['power'];
    	
   		 
    	import('ORG.Util.Page');// 导入分页类
		$pre=12;//每页多少条
    	if($power==4){
	    	$count      = $user->count();// 查询满足要求的总记录数 $map表示查询条件
	    }else{
	    	$count      = $user->where("power < 4")->count();// 查询满足要求的总记录数 $map表示查询条件
	    }
	    
	    $Page       = new \Think\Page($count,$pre);// 实例化分页类 传入总记录数
   
	    
    	$show       = $Page->show();// 分页显示输出

	    // 进行分页数据查询
	    if($power==4){
	    	$list = $user->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	    }else{
	    	$list = $user->where("power < 4")->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	    }
	    
	    $this->assign('user_list',$list);// 赋值数据集
	   
	    $this->assign('page',$show);// 赋值分页输出
    	
    
		$this->display("user_list");
    }
    
	public function AddUser(){
		$this->assign('isedit',0);
		$this->display("user_add");
    }
    
    
	public function EditUser(){
		$id=$_GET["id"];
		$user = M('user');
		$list= $user->where("id=$id")->find();
		$this->assign('vo',$list);
		$this->assign('isedit',1);
		$this->display("user_add");
    }
    
	public function add(){

		
		$user = M('user');
	    $data=$user->create();
	    
	    $data["account"]=$_POST["account"];
	    $data["password"]=$_POST["password"];
	    $data["email"]=$_POST["email"];
	    $data["power"]=$_POST["power"];
	    
	    $data["name"]=$_POST["name"]?$_POST["name"]:"";
	    $data["des"]=$_POST["des"]?$_POST["des"]:"";
	    $data["created_time"]=Date("Y-m-d H:i:s");
	    
	    if($_POST["isedit"]==0){
	    
	    //账号不能重复
	    $isaccount=$user->where("account='".$_POST["account"]."'")->find();
	    
	    if($isaccount){
	    	$this->success('用户新增失败！已存在当前用户名', U('Admin/User/AddUser', '', false, true));
	    	exit;
	    }
	    
			$result=$user->add($data);
	        
			if($result !== false){
		        $this->success('用户新增成功！', U('Admin/User/Index', '', false, true));
		    }else{
		        $this->error("用户新增失败", U('Admin/User/AddUser', '', false, true));
		    }
		    
	    }elseif($_POST["isedit"]==1){
	    	$id=$_POST["id"];
	    	
	    	
			$result=$user->where("id=$id")->save($data);
	        
			if($result !== false){
		        $this->success('用户修改成功！', U('Admin/User/Index', '', false, true));
		    }else{
		        $this->error("用户修改失败", U('Admin/User/Index', "id=$id", false, true));
		    }
	    	
	    }    
			
    }
    
    public function delete(){
    		$id=$_POST["radio_del"];
    		$user = M('user');
	    	$result=$user->where("id=$id")->delete();
	    	
    		if($result !== false){
				 $this->success("用户删除成功 ！", U('Admin/User/Index', '', false, true));
			}else{
				 $this->success('用户删除失败！', U('Admin/User/Index', '', false, true));
			}
    }
}